<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <title>WebSocket</title>
</head>
<body>

<div>发送消息:</div>
<input type="text" id="msgContent"/>
<input type="button" value="点我发送" onclick="CHAT.chat()"/>
<div>接收消息:</div>
<div id="receiveMsg" style="background-color: beige"></div>

<script type="application/javascript">
    window.CHAT = {
        socket: null,
        init: function () {
            if (window.WebSocket) {
                CHAT.socket = new WebSocket("ws://192.168.31.167:8088/ws");
                CHAT.socket.onopen = function () {
                    console.log("客户端和服务器建立连接成功!");
                };
                CHAT.socket.onclose = function () {
                    console.log("客户端和服务器建立连接关闭!");
                };
                CHAT.socket.onerror = function (e) {
                    console.log(e);
                    console.log("发成错误!");
                };
                CHAT.socket.onmessage = function (event) {
                    console.log("接收到消息:" + event.data);
                    var receiveMsg = document.getElementById("receiveMsg");
                    var html = receiveMsg.innerHTML;
                    receiveMsg.innerHTML = html + "<br/>" + event.data
                }
            } else {
                alert("当前浏览器不支持 WebSocket");
            }
        },
        chat: function () {
            var msg = document.getElementById("msgContent");
            CHAT.socket.send(msg.value);
        }
    };

    CHAT.init()

</script>

</body>
</html>